package xyz.zchao.blog.service.impl;

import org.springframework.stereotype.Service;
import xyz.zchao.blog.dao.UserMapper;
import xyz.zchao.blog.exception.CustomizeException;
import xyz.zchao.blog.pojo.User;
import xyz.zchao.blog.service.UserService;
import xyz.zchao.blog.util.EncryptionUtil;
import xyz.zchao.blog.util.ResultCode;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 根据用户名查找用户,用户不存在则抛出异常
     * @param userName
     * @return
     * @throws CustomizeException
     */
    @Override
    public User findUserByUserName(String userName) throws CustomizeException {
        User user=userMapper.selectByUserName(userName);
        if (user == null) {
            throw new CustomizeException(ResultCode.USER_NOT_FOUND);
        }
        return user;
    }

    @Override
    public User findUserByRoleId(Integer roleId) {
        User user = userMapper.selectByUserRoleId(roleId);
        if (user == null) {
            throw new CustomizeException(ResultCode.USER_NOT_FOUND);
        }
        return user;
    }

    /**
     * 添加用户
     * @param record
     * @return
     */
    @Override
    public int create(User record) {
        try {
            record.setUserPassword(EncryptionUtil.encrypted(record.getUserPassword()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return userMapper.insertSelective(record);
    }

    @Override
    public User retrieveById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteById(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(User record) {
        if (record.getUserPassword() != null) {
            try {
                record.setUserPassword(EncryptionUtil.encrypted(record.getUserPassword()));
            } catch (Exception e) {
                throw new CustomizeException(ResultCode.ENCRYPT_DECRYPT_ERROR);
            }
        }
        return userMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int getCount() {
        return userMapper.getCount();
    }

    @Override
    public List<User> retrieveAllByPaging(Integer page, Integer limit) {
        return userMapper.selectUsersByPaging(page, limit);
    }

    @Override
    public List<User> fuzzyFindUserByUserName(String userName) {
        return userMapper.fuzzyQueryUserByUserName(userName);
    }
}
